package com.aiwu.bean;

import androidx.annotation.Nullable;

import com.aiwu.memory.MemoryManager;

import java.io.Serializable;

/**
 * 内存
 */
public class MemoryBean implements Serializable {
    //正负的界限值
    private final static long POSITIVE_FLAG = 2147483647L;
    //计算负数值的时候要减去这个数
    public final static long NEGATIVE_FLAG = 4294967296L;
    private long address;
    private long value;
    private boolean isSelected;
    private boolean isLocking;

    public long getAddress() {
        return address;
    }

    public void setAddress(long address) {
        this.address = address;
    }

    public long getValue() {
        return value;
    }

    public void setValue(long value) {
        this.value = value;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }

    public boolean isLocking() {
        return isLocking;
    }

    public void setLocking(boolean locking) {
        isLocking = locking;
    }

    public String getAddressStr() {
        return MemoryManager.Long2Hex(address, false);
    }

    public String getValueStr() {
        return getValueStr(true);
    }

    /**
     * 获取值
     *
     * @param radixTen true 10进制 false 16进制
     * @return
     */
    public String getValueStr(boolean radixTen) {
        if (radixTen) {
            if (value > POSITIVE_FLAG) {//负数
                int realValue = (int) (value - NEGATIVE_FLAG);
                String floatStr = Float.toString(Float.intBitsToFloat(realValue));
                if (isFloat(floatStr)) {
                    return floatStr;
                } else {
                    return Integer.toString(realValue);
                }
            } else {//正数
                String floatStr = Float.toString(Float.intBitsToFloat((int) value));
                if (isFloat(floatStr)) {
                    return floatStr;
                } else {
                    return Long.toString(value);
                }
            }
        } else {
            return MemoryManager.Long2Hex(value, false);
        }
    }

    private boolean isFloat(String str) {
        return !str.contains("E") && !str.equalsIgnoreCase("NaN");
    }

    /**
     * 地址防重复
     */
    @Override
    public boolean equals(@Nullable Object obj) {
        if (obj instanceof MemoryBean) {
            return address == ((MemoryBean) obj).address;
        } else {
            return false;
        }
    }

    /**
     * 地址防重复
     */
    public int hashCode() {
        return (int) address;
    }
}
